package com.example.administrator.sdscanner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.storage.StorageManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beaglebuddy.mp3.MP3;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.server.LocalSocketHttpServer;

import org.apache.commons.codec.binary.Base64;
import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import bean.MP3Info;
import music.Music;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import util.AudioParse;
import util.DBUtil;
import util.HttpUtil;
import util.Scanner;
import util.UrlParse;
import util.Util;

public class MainActivity extends AppCompatActivity {

    public static boolean indexFlag = true;
    public static Context context;

    private Scanner scanner;
    private AudioParse audio;
    private List<MP3Info> scanList = new ArrayList<>();
    private WebView webView;
    private FrameLayout frame;
    private FragmentTransaction transaction;

    private MyVolumeReceiver mVolumeReceiver;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e("message:", "!!!!!");
            MP3 mp3 = (MP3) msg.obj;
            mp3.setAudioDuration();

            System.out.println("歌名：" + mp3.getTitle() + "\n歌手：" + mp3.getLeadPerformer() + "\n专辑：" + mp3.getAlbum());
            System.out.println("文件大小：" + Util.convertM(mp3.getFileSize())+ "M");
            System.out.println("时长:" + Util.secondToTime(mp3.getAudioDuration()));
            System.out.println("比特率：" + mp3.getBitrate() + "Kbps");
            System.out.println("采样率：" + (mp3.getFrequency() / 1000.0) + "KHz");
//            JSONObject obj = new JSONObject();
//            obj.put("title", mp3.getTitle() != null ? mp3.getTitle() : "未知");
//            obj.put("artist", mp3.getLeadPerformer() != null ? mp3.getLeadPerformer() : "未知");
//            obj.put("fileSize", Util.convertM(mp3.getFileSize())+ "M" );
//            obj.put("time", Util.secondToTime(mp3.getAudioDuration()));
//            obj.put("bit", mp3.getBitrate() + "Kbps");
//            obj.put("fre", (mp3.getFrequency() / 1000.0) + "KHz");

//            if (mp3.getPictures().size() >= 1) {
//                obj.put("img", "data:" + mp3.getPictures().get(0).getMimeType() + ";base64," + new String(Base64.encodeBase64(mp3.getPictures().get(0).getImage())));
//            } else {
//                obj.put("img", "");
//            }
            MP3Info info = new MP3Info();
            info.setPath(mp3.getPath());
            info.setFileName(mp3.getPath().substring(mp3.getPath().lastIndexOf('/')));
            info.setName(mp3.getTitle() != null ? mp3.getTitle() : "未知");
            info.setArtist(mp3.getLeadPerformer() != null ? mp3.getLeadPerformer() : "未知");
            info.setAlbum(mp3.getAlbum() != null ? mp3.getAlbum() : "未知");
            info.setBitrate(mp3.getBitrate());
            info.setFrequency(mp3.getFrequency() / 1000.0);
            info.setDuration(mp3.getAudioDuration());
            info.setSize(Util.convertM(mp3.getFileSize()));
            info.setLyric(mp3.getLyrics() != null ? mp3.getLyrics() : "暂无歌词");
            scanList.add(info);
            if (!DataSupport.isExist(MP3Info.class, "path=?", info.getPath())) {
                if (DataSupport.count(MP3Info.class) > 0) {
                    info.setId(DataSupport.findLast(MP3Info.class).getId() + 1);
                } else {
                    info.setId(0);
                }
                if (!info.getName().equals("未知") && !info.getArtist().equals("未知")) {
                    queryFormServer("http://gecimi.com/api/lyric/" + info.getName() + "/" + info.getArtist());
                }
                webView.loadUrl("JavaScript:MusicInfo.localList.push(" + JSONObject.toJSON(info) + ")");
                Music.cacheList.add(info);
                info.save();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        context = getApplicationContext();
        super.onCreate(savedInstanceState);
        // 隐藏ActionBar工具栏
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        setContentView(R.layout.activity_main);

        // 设置WebView可以调试
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        // 设置透明状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }

        // 异步调试
        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(
                                Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(
                                Stetho.defaultInspectorModulesProvider(this))
                        .build());


        Music.m = new MediaPlayer();
        init();
    }

    public static Context getContext() {
        return context;
    }

    private void init(){

        Music.cacheList = DataSupport.findAll(MP3Info.class);
        // 设置播放完成监听事件
        Music.m.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Music.playPatter();
            }
        });

        // 获取歌词请求
//        for (int i = 0; i <= Music.cacheList.size() - 1; i++){
//            if (!Music.cacheList.get(i).getName().equals("未知") && !Music.cacheList.get(i).getArtist().equals("未知")){
//                queryFormServer("http://gecimi.com/api/lyric/" + Music.cacheList.get(i).getName() + "/" + Music.cacheList.get(i).getArtist());
//            }
//        }

        // 扫描
        String[] sd = getSdPath();
        for (String str : sd){
            System.out.println("外存储：" + str);
        }
        // 初始化音乐管理类
        Music.mManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        // 获取音乐最大音量
        Music.maxVolume = Music.mManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        Music.currentVolume = Music.mManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        System.out.println("max volume: " + Music.maxVolume + "   current volume: " + Music.currentVolume);

        webView  = (WebView) findViewById(R.id.webView);
        Music.webView = webView;
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示
        webView.setOnLongClickListener(new View.OnLongClickListener(){
            @Override
            public boolean onLongClick(View view) {
                return true;
            }
        });
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 根据传入的参数去加载新的网页
                view.loadUrl(url);
                // 表示当前WebView可以处理打开新网页的请求，不用借助系统浏览器
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                view.loadUrl("JavaScript:initInfo = " + JSONArray.toJSON(Music.cacheList));
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

        webView.setWebChromeClient(new WebChromeClient(){

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100){
                    // 注册音量变化广播接收者
                    myRegisterReceiver();
                    webView.loadUrl("JavaScript:MusicInfo.volume=" + Music.currentVolume + "; MusicInfo.maxVolume=" + Music.maxVolume +";");
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                Log.i("Alert", message);
                return true;
            }

            @Override
            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
//                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                Log.i("Console", message);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                Log.i("url:", url.toString());
                System.out.println("message:" + message + "value:" + defaultValue);
                UrlParse parse = new UrlParse();
                parse.parse(message, defaultValue);

                result.confirm();
                return true;
            }


        });

        webView.addJavascriptInterface(new Scanner(getSdPath(), handler), "search");
        webView.addJavascriptInterface(new Music(), "Music");
        webView.addJavascriptInterface(new DBUtil(), "load");
        webView.loadUrl("file:///android_asset/Music/index.html");
    }

    private String[] getSdPath(){
        StorageManager manager = (StorageManager) this.getSystemService(STORAGE_SERVICE);
        try {
            Method methodGetPaths = manager.getClass().getMethod("getVolumePaths");
            String[] paths = (String[]) methodGetPaths.invoke(manager);
            return paths;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从服务器查询歌词信息
     * @param address 地址
     */
    private void queryFormServer(String address){
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("Http to get lyric", "have a error");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();
                System.out.println(responseText);
                if (!responseText.contains("The resource could not be found.")){
                    JSONObject o = JSONObject.parseObject(responseText);
                    if (o.get("result") != null){
                        JSONArray array = JSONArray.parseArray(o.get("result").toString());
                        if (array.size() > 0){
                            JSONObject result = JSONObject.parseObject(array.get(0).toString());
                            String url = (String) result.get("lrc");
                            HttpUtil.wrtieContentFromUrl(url, result.get("song") + ".lrc");
                            Log.i("result", result.get("lrc").toString());
                            System.out.println(result.toJSONString());
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (indexFlag){
            onStop();
            moveTaskToBack(true);
        } else {
            webView.loadUrl("JavaScript:UIFrame.showMusicPage();");
        }
    }

    /**
     * 注册当音量发生变化时接收的广播
     */
    private void myRegisterReceiver(){
        mVolumeReceiver = new MyVolumeReceiver() ;
        IntentFilter filter = new IntentFilter() ;
        filter.addAction("android.media.VOLUME_CHANGED_ACTION") ;
        registerReceiver(mVolumeReceiver, filter) ;
    }

    /**
     * 处理音量变化时的界面显示
     * @author long
     */
    private class MyVolumeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //如果音量发生变化则更改页面UI
            if(intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")){
                Music.currentVolume = Music.mManager.getStreamVolume(AudioManager.STREAM_MUSIC) ;// 当前的媒体音量
                webView.loadUrl("JavaScript:UIFrame.updateProView($('.ms-audio-volume'), Math.floor(" + Music.currentVolume + " / " + Music.maxVolume + " * 100) + '%');"); ;
            }
        }
    }
}
